package com.nxk.modules.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


@Component
public class FileUpload {

    private Logger logger = LoggerFactory.getLogger(FileUpload.class);

    @Value("${file.fileUploadPath}")
    private String fileUploadPath;

    @Value("${file.urlPath}")
    private String urlPath;

    public String fileUpload(MultipartFile file, HttpServletRequest request){
        if (file==null || file.isEmpty()) {
            logger.error("文件为空!");
            return null;
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(fileUploadPath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = urlPath + fileName;
        return url;
    }

}
